package root.ResponseTimeScheduling;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class ResponseTimeScheduler {

    List<Task> tasks;

    public ResponseTimeScheduler(List<Task> tasks) {
        this.tasks = tasks;
    }

    public void schedule() {
        // 按照到达时间排序任务
        tasks.sort(Comparator.comparingInt(task -> task.arrivalTime));

        int currentTime = 0; // 当前时间
        List<Task> completedTasks = new ArrayList<>();

        // 执行调度
        while (completedTasks.size() < tasks.size()) {
            Task nextTask = null;

            // 找出当前时间内到达的任务
            for (Task task : tasks) {
                if (!completedTasks.contains(task) && task.arrivalTime <= currentTime) {
                    if (nextTask == null || task.burstTime < nextTask.burstTime) {
                        nextTask = task;
                    }
                }
            }

            // 如果有任务需要执行
            if (nextTask != null) {
                nextTask.startTime = currentTime;
                nextTask.calculateFinishTime();
                nextTask.calculateResponseTime();
                completedTasks.add(nextTask);
                currentTime = nextTask.finishTime;
            } else {
                // 如果没有任务可以执行，时间推进
                currentTime++;
            }
        }

        // 输出任务调度的结果
        System.out.println("Task Scheduling Results:");
        for (Task task : tasks) {
            System.out.println("Task - Arrival Time: " + task.arrivalTime + ", Burst Time: " + task.burstTime +
                    ", Start Time: " + task.startTime + ", Finish Time: " + task.finishTime +
                    ", Response Time: " + task.responseTime);
        }
    }
}
